#include <QtNetwork>

#include "jconn.h"

JConn::JConn(QObject *parent) :
    QTcpSocket(parent)
{
    pending_read=0;
    connect(this,SIGNAL(readyRead()),this,SLOT(recv_slot()));
    connect(this,SIGNAL(disconnected()),this,SLOT(disconnect_slot()));
    info.state=false;
}

JConn::~JConn()
{

}

void JConn::recv_slot()
{
    QByteArray info_str;
    QList <QByteArray> tmp;
    info_str = this->readLine();
    if(info_str=="__INFORMATION__\n")
    {
        while(this->bytesAvailable()>0)
        {
            info_str = this->readLine();
            tmp = info_str.split('-');
            if(tmp.size()>0)
            {
                switch(tmp[0].toInt()){
                case 1:{
                        info.cpu.user=tmp[2].toInt();
                        info.cpu.system=tmp[3].toInt();
                        info.cpu.nice=tmp[4].toInt();
                        info.cpu.idle=tmp[5].toInt();
                        info.cpu.wait=tmp[6].toInt();                        
                        this->info.state=true;
                    };break;
                case 2:{
                        info.mem.used=tmp[2].toInt();
                        info.mem.cached=tmp[3].toInt();
                        info.mem.shared=tmp[4].toInt();
                        info.mem.bufferd=tmp[5].toInt();
                        info.mem.swapped=tmp[6].toInt();
                    };break;
                case 3:{
                        info.temp.temp=tmp[2].toInt();
                    };break;
                case 4:{
                        info.traffic.in=tmp[2].toInt();;
                        info.traffic.out=tmp[3].toInt();

                    };break;
                case 5:{
                        if(info.hostname.size()==0)
                        {
                            info.hostname=tmp[2];
                            info.hostaddr=this->peerAddress();
                        }
                    };break;
                default:break;
                }
            }
        }
        info.update_time = QDateTime::currentDateTime();
        emit data_ready();
    }
    pending_read=1;

    this->tmp = info_str;
}

void JConn::close()
{
    QTcpSocket::close();
}

void JConn::disconnect_slot()
{
    this->ConnectionState=Disconnect;
    info.state = false;

}
